package _mst;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 面试题 03.03. 堆盘子
 */
public class T0303 {
    private final List<Deque<Integer>> list;
    private final int cap;

    public T0303(int cap) {
        list = new ArrayList<>();
        this.cap = cap;
    }

    public void push(int val) {
        if (cap == 0) return;
        if (list.isEmpty() || list.get(list.size() - 1).size() == cap) {
            Deque<Integer> stack = new LinkedList<>();
            stack.push(val);
            list.add(stack);
        } else list.get(list.size() - 1).push(val);
    }

    public int pop() {
        if (list.isEmpty()) return -1;
        Deque<Integer> stack = list.get(list.size() - 1);
        Integer pop = stack.pop();
        if (stack.isEmpty()) list.remove(list.size() - 1);
        return pop;
    }

    public int popAt(int index) {
        if (list.size() <= index) return -1;
        Deque<Integer> stack = list.get(index);
        Integer pop = stack.pop();
        if (stack.isEmpty()) list.remove(index);
        return pop;
    }
}
